<!-- vertical-slider.vue -->

<template>
  <view class="vertical-slider" :style="{ height: height + 'px' }">
    <view class="slider" :style="{ height: (value - min) / (max - min) * 100 + '%' }">
      <view class="thumb" :style="{ bottom: (value - min) / (max - min) * 100 + '%' }" @touchstart="onThumbTouchStart" @touchmove="onThumbTouchMove" @touchend="onThumbTouchEnd"></view>
    </view>
  </view>
</template>

<script>
  export default {
    name: 'VerticalSlider',
    props: {
      value: {
        type: Number,
        default: 1
      },
      min: {
        type: Number,
        default: 0.5
      },
      max: {
        type: Number,
        default: 2
      },
      height: {
        type: Number,
        default: 200
      }
    },
    data() {
      return {
        isDragging: false,
        startY: 0,
        startValue: 0
      }
    },
    methods: {
      onThumbTouchStart(event) {
        this.isDragging = true
        this.startY = event.touches[0].clientY
        this.startValue = this.value
      },
      onThumbTouchMove(event) {
        if (!this.isDragging) return
        this.$nextTick(() => {
          uni.createSelectorQuery().in(this).select('.slider').boundingClientRect(data => {
            const sliderHeight = data.height
            const diff = this.startY - event.touches[0].clientY
            const range = this.max - this.min
            const value = this.startValue + (diff / sliderHeight) * range
            this.setValue(value)
          }).exec()
        })

      },
      onThumbTouchEnd(event) {
        this.isDragging = false
      },
      setValue(value) {
        if (value < this.min) value = this.min
        if (value > this.max) value = this.max
        this.$emit('change', value)
      }
    }
  }
</script>

<style>
  .vertical-slider {
    position: relative;
    width: 10px;
  }
  .slider {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ddd;
    border-radius: 5px;
  }
  .thumb {
    position: absolute;
    bottom: -10px;
    left: 0;
    width: 20px;
    height: 20px;
    background-color: #fff;
    border-radius: 50%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    touch-action: none;
  }
</style>
